<template>
  <div class="packages-page">
    <el-page-header>
      <template slot="content">
        <h1>包管理</h1>
        <p>浏览和管理npm包</p>
      </template>
    </el-page-header>
    
    <el-card class="search-card">
      <div class="search-form">
        <el-input 
          v-model="searchQuery"
          placeholder="搜索包名称或描述"
          prefix-icon="el-icon-search"
          style="width: 300px; margin-right: 16px;"
          @keyup.enter.native="searchPackages"
        />
        
        <el-select 
          v-model="selectedTag"
          placeholder="选择标签"
          style="width: 180px; margin-right: 16px;"
          @change="searchPackages"
        >
          <el-option label="全部" value="" />
          <el-option 
            v-for="tag in tags"
            :key="tag.id"
            :label="tag.name"
            :value="tag.id"
          />
        </el-select>
        
        <el-button type="primary" @click="searchPackages">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </el-card>
    
    <el-card class="packages-card">
      <template slot="header">
        <div class="card-header">
          <span>包列表</span>
          <el-button type="primary" size="small" @click="showCreatePackageDialog">新增包</el-button>
        </div>
      </template>
      
      <el-table 
        v-loading="loading"
        :data="packages"
        style="width: 100%"
      >
        <el-table-column prop="name" label="包名" width="180" />
        <el-table-column prop="version" label="版本" width="100" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="downloads" label="下载量" width="100" align="right" />
        <el-table-column prop="lastUpdated" label="最后更新" width="160" />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button 
              type="text" 
              size="small" 
              @click="viewPackageDetails(scope.row)"
            >
              详情
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="editPackage(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              danger 
              @click="deletePackage(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </el-card>
    
    <!-- 创建/编辑包对话框 -->
    <el-dialog 
      :title="isEditing ? '编辑包' : '创建包'"
      :visible.sync="packageDialogVisible"
      width="600px"
    >
      <el-form 
        ref="packageForm"
        :model="packageForm"
        :rules="packageRules"
        label-width="80px"
      >
        <el-form-item label="包名" prop="name">
          <el-input v-model="packageForm.name" placeholder="请输入包名" />
        </el-form-item>
        <el-form-item label="版本" prop="version">
          <el-input v-model="packageForm.version" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="packageForm.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="packageForm.author" placeholder="请输入作者名" />
        </el-form-item>
        <el-form-item label="下载量">
          <el-input v-model.number="packageForm.downloads" placeholder="请输入下载量" />
        </el-form-item>
        <el-form-item label="标签">
          <el-select 
            v-model="packageForm.tags"
            multiple
            placeholder="请选择标签"
          >
            <el-option 
              v-for="tag in tags"
              :key="tag.id"
              :label="tag.name"
              :value="tag.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="packageDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePackage">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'PackagesPage',
  layout: 'default',
  data() {
    return {
      packages: [],
      tags: [],
      loading: false,
      searchQuery: '',
      selectedTag: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 包表单相关
      packageDialogVisible: false,
      isEditing: false,
      currentPackageId: null,
      packageForm: {
        name: '',
        version: '',
        description: '',
        author: '',
        downloads: 0,
        tags: []
      },
      packageRules: {
        name: [
          { required: true, message: '请输入包名', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        version: [
          { required: true, message: '请输入版本号', trigger: 'blur' },
          { pattern: /^\d+\.\d+\.\d+$/, message: '版本号格式不正确', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' }
        ]
      }
    }
  },
  async fetch() {
    await this.loadPackages()
    await this.loadTags()
  },
  methods: {
    async loadPackages() {
      this.loading = true
      try {
        const response = await this.$axios.get('/packages', {
          params: {
            query: this.searchQuery,
            tagId: this.selectedTag,
            page: this.currentPage,
            pageSize: this.pageSize
          }
        })
        this.packages = response.items || []
        this.total = response.total || 0
      } catch (error) {
        this.$message.error('加载包列表失败：' + error.message)
      } finally {
        this.loading = false
      }
    },
    
    async loadTags() {
      try {
        const response = await this.$axios.get('/tags')
        this.tags = response || []
      } catch (error) {
        this.$message.error('加载标签失败：' + error.message)
      }
    },
    
    async searchPackages() {
      this.currentPage = 1
      await this.loadPackages()
    },
    
    resetSearch() {
      this.searchQuery = ''
      this.selectedTag = ''
      this.searchPackages()
    },
    
    handleSizeChange(size) {
      this.pageSize = size
      this.loadPackages()
    },
    
    handleCurrentChange(current) {
      this.currentPage = current
      this.loadPackages()
    },
    
    viewPackageDetails(pkg) {
      this.$router.push(`/packages/${pkg.id}`)
    },
    
    showCreatePackageDialog() {
      this.isEditing = false
      this.currentPackageId = null
      this.resetPackageForm()
      this.packageDialogVisible = true
    },
    
    async editPackage(pkg) {
      this.isEditing = true
      this.currentPackageId = pkg.id
      
      try {
        const response = await this.$axios.get(`/packages/${pkg.id}`)
        const packageDetails = response
        
        this.packageForm = {
          name: packageDetails.name,
          version: packageDetails.version,
          description: packageDetails.description,
          author: packageDetails.author,
          downloads: packageDetails.downloads || 0,
          tags: packageDetails.tags ? packageDetails.tags.map(tag => tag.id) : []
        }
        
        this.packageDialogVisible = true
      } catch (error) {
        this.$message.error('加载包详情失败：' + error.message)
      }
    },
    
    resetPackageForm() {
      this.packageForm = {
        name: '',
        version: '',
        description: '',
        author: '',
        downloads: 0,
        tags: []
      }
      
      if (this.$refs.packageForm) {
        this.$refs.packageForm.resetFields()
      }
    },
    
    async savePackage() {
      this.$refs.packageForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.isEditing) {
              await this.$axios.put(`/packages/${this.currentPackageId}`, this.packageForm)
              this.$message.success('包更新成功')
            } else {
              await this.$axios.post('/packages', this.packageForm)
              this.$message.success('包创建成功')
            }
            
            this.packageDialogVisible = false
            await this.loadPackages()
          } catch (error) {
            this.$message.error('保存失败：' + error.message)
          }
        }
      })
    },
    
    async deletePackage(id) {
      this.$confirm('确定要删除这个包吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.$axios.delete(`/packages/${id}`)
          this.$message.success('删除成功')
          await this.loadPackages()
        } catch (error) {
          this.$message.error('删除失败：' + error.message)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.packages-page {
  padding: 24px;
}

.search-card {
  margin-bottom: 24px;
}

.search-form {
  display: flex;
  align-items: center;
  padding: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.packages-card {
  margin-bottom: 24px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>